/*
 * @Author: zyk 997610780@qq.com
 * @Date: 2022-10-11 12:18:48
 * @LastEditors: zyk 997610780@qq.com
 * @LastEditTime: 2022-10-13 14:13:40
 * @FilePath: \fifty-small-projects\41验证码输入框\41.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 验证码的长度
let code_length = 6
let is_focus = true
// 盒子类型 0：方框 1：下划线 2：中线
let box_type = 1
let box_class_type = ['square','underline','midline']
// 输入的内容
let content = ""
// 文本替换符号
let replace_sign = '*'
let input_box_list = document.querySelector('.input_box_list')

let input_el = document.querySelector('.input_el')
input_el.setAttribute('maxlength', code_length)

// 创建输入框盒子
function createdInputBox() {
  let input_box = document.createElement('div')
  input_box.classList.add('input_box')
  input_box.classList.add(box_class_type[box_type])
  return input_box
}


// 创建输入框中的中线
function createdLine() {
  let line = document.createElement('div')
  line.classList.add('line')
  return line
}
let input_boxs = []
// 加载输入框
function loadInputBox() {
  for (let i = 0; i < code_length; i++) {
    input_box_list.appendChild(createdInputBox())
  }
  input_boxs = document.querySelectorAll('.input_box')
  if (is_focus) {
    input_el.focus()
    boxTextChange()
  }
}
loadInputBox()


input_el.addEventListener('focus', () => {
  is_focus = true
  if (content.length < code_length) {
    setActiveStatus(content.length)
  }
})

input_el.addEventListener('blur',()=>{
  is_focus = false
  input_boxs.forEach((item,index)=>{
    if(!item.innerText){
      initBoxStatus(index)
    }
  })
})

input_el.addEventListener('input', () => {
  content = input_el.value
  if (content.length <= code_length) {
    boxTextChange()
  }
})

function boxTextChange() {
  input_boxs.forEach((item,index) => {
    initBoxStatus(index)
  })
  for (let i = 0; i < content.length; i++) {
    if(replace_sign){
      console.log(content);
      fillContent(replace_sign,i)
    }else{
      fillContent(content[i],i)
    }
  }
  if (content.length < code_length) {
    setActiveStatus(content.length)
  }
  input_boxs.forEach(item=>{
    if(item.innerText){
      item.classList.remove('active')
      if(box_type <=1){
        item.classList.add('finish')
      }else{
        item.classList.remove(box_class_type[box_type])
      }
    }else{
      item.classList.remove('finish')
    }
  })
}

// 初始化盒子的状态
function initBoxStatus(i){
  input_boxs[i].className = `input_box ${box_class_type[box_type]}`
  input_boxs[i].innerHTML = ''
}

// 填充盒子内容
function fillContent(v,i){
  input_boxs[i].innerText = v
}
// 设置盒子聚焦状态
function setActiveStatus(i){
  input_boxs[i].appendChild(createdLine())
  input_boxs[i].classList.add('active')
}